﻿using BrightIdeasSoftware;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FormTest
{
    public partial class LogDetailForm : Form
    {
        private VirtualObjectListView _vOlv;
        private List<SystemLog> _logs = new List<SystemLog>();
        private ImageList _logImageList;
        public LogDetailForm()
        {
            InitializeComponent();
            InitializeImageList();
            InitializeVirtualListView();
            // 异步加载10万条示例数据（避免UI阻塞）
            LoadDataAsync();
        }

        // 初始化图标列表
        private void InitializeImageList()
        {
            _logImageList = new ImageList
            {
                ImageSize = new Size(16, 16),
                ColorDepth = ColorDepth.Depth32Bit
            };

            // 添加日志级别图标
            _logImageList.Images.Add("Info",SystemIcons.Warning);
            _logImageList.Images.Add("Warning", SystemIcons.Error);
            _logImageList.Images.Add("Error", SystemIcons.Information);
            _logImageList.Images.Add("Fatal", SystemIcons.Question);
        }

        // 初始化VirtualObjectListView
        private void InitializeVirtualListView()
        {
            _vOlv = new VirtualObjectListView
            {
                Dock = DockStyle.Fill,
                View = View.Details,
                FullRowSelect = true,
                GridLines = true,
                // 虚拟模式优化
                VirtualListSize = 0,
                //CacheVirtualItems+=, // 启用缓存提升性能
                // 外观设置
                UseAlternatingBackColors = true,
                RowHeight = 24,
                SmallImageList = _logImageList, // 关联图标列表
                // 交互设置
                //AllowColumnReordering = true,
                HeaderWordWrap = true
            };

            // 配置列
            _vOlv.Columns.AddRange(new OLVColumn[]
            {
                // 图标列（根据日志级别显示不同图标）
                new OLVColumn("", "")
                {
                    Width = 30,
                    ImageGetter = GetLogLevelIcon // 图标获取器
                },
                new OLVColumn("ID", "Id") { Width = 80 },
                new OLVColumn("时间", "Timestamp")
                {
                    Width = 180,
                    AspectToStringConverter = val => ((DateTime)val).ToString("yyyy-MM-dd HH:mm:ss.fff")
                },
                new OLVColumn("级别", "Level") { Width = 80 },
                new OLVColumn("来源", "Source") { Width = 150 },
                new OLVColumn("消息", "Message") { Width = 500 }
            });

            // 自定义级别列颜色
            _vOlv.FormatCell += (s, e) =>
            {
                if (e.Column.AspectName == "Level" && e.Model is SystemLog log)
                {
                    //e.SubItem.ForeColor = log.Level
                    //{
                    //    "Fatal" => Color.DarkRed,
                    //    "Error" => Color.Red,
                    //    "Warning" => Color.Orange,
                    //    _ => Color.Green
                    //};
                }
            };
            //// 双击查看详情
            //_vOlv.DoubleClick += (s, e) =>
            //{
            //    if (_vOlv.SelectedObject is SystemLog selectedLog)
            //    {
            //        new LogDetailForm(selectedLog).ShowDialog();
            //    }
            //};

            Controls.Add(_vOlv);
        }

        // 根据日志级别获取图标索引
        private object GetLogLevelIcon(object rowObject)
        {
            if (rowObject is SystemLog log)
            {
                //return log.Level switch
                //{
                //    "Warning" => "Warning",
                //    "Error" => "Error",
                //    "Fatal" => "Fatal",
                //    _ => "Info"
                //};
            }
            return "Info"; // 默认图标
        }

        // 异步加载数据
        private async void LoadDataAsync()
        {
            var statusLabel = new Label { Text = "加载数据中...", Dock = DockStyle.Top };
            Controls.Add(statusLabel);
            Controls.SetChildIndex(statusLabel, 0);

            // 在后台线程生成数据
            _logs = await System.Threading.Tasks.Task.Run(() => GenerateLogs(100000));

            // 绑定数据到虚拟列表
            _vOlv.SetObjects(_logs);

            // 初始排序（按时间降序）
            //_vOlv.Sort(_vOlv.Columns[2], SortOrder.Descending);

            statusLabel.Text = $"加载完成，共 {_logs.Count:N0} 条日志";
        }

        // 生成示例日志数据
        private List<SystemLog> GenerateLogs(int count)
        {
            var logs = new List<SystemLog>();
            var levels = new[] { "Info", "Warning", "Error", "Fatal" };
            var sources = new[] { "System", "Network", "Application", "Security", "Database" };
            var rnd = new Random();
            var now = DateTime.Now;

            for (int i = 0; i < count; i++)
            {
                var level = levels[rnd.Next(levels.Length)];
                logs.Add(new SystemLog
                {
                    Id = i + 1,
                    Timestamp = now.AddMinutes(-(count - i)),
                    Level = level,
                    Source = sources[rnd.Next(sources.Length)],
                    Message = $"{level} message from {sources[rnd.Next(sources.Length)]} - entry #{i + 1}"
                });
            }
            return logs;
        }

    }
    // 数据模型
    public class SystemLog
    {
        public long Id { get; set; }
        public DateTime Timestamp { get; set; }
        public string Level { get; set; } // Info, Warning, Error, Fatal
        public string Source { get; set; }
        public string Message { get; set; }
    }
}
